import React from 'react';
import { connect } from 'dva';
import { Menu, Icon } from 'antd';
import { Link } from 'dva/router';
import { getOpenKeysByMenuKey } from '../../../constants/constants.js';
import './index.less';

const { SubMenu } = Menu;

@connect((state) => {
  return { ...state.app, loading: state.loadingBar === 1 };
})
export default class SiderMenu extends React.Component {
  menuItemOnClick = (key) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'app/save',
      payload: {
        current: key,
      },
    });
  }
  createMenuItem = (data, isFirst) => {
    const { collapsed } = this.props;
    const loginUser = sessionStorage.getItem('loginUser');
    const loginUserObj = JSON.parse(loginUser);
    const spanStyle = isFirst ? { display: collapsed ? 'none' : 'inline-block' } : { display: 'inline-block' };
    const menuDom = data.map((menu) => {
      if (menu.role.indexOf(loginUserObj.role) >= 0) {
        if (menu.isParent) {
          const title = (
            <span>
              <Icon type={menu.icon} />
              <span style={spanStyle} >
                {menu.name}
              </span>
            </span>
          );
          const subMenu = this.createMenuItem(menu.subMenu, false);
          return (
            <SubMenu key={menu.key} title={title} >
              {subMenu}
            </SubMenu>
          );
        } else {
          return (
            <Menu.Item key={menu.key}>
              <Link to={menu.path} onClick={() => this.menuItemOnClick(menu.key)}>
                <Icon type={menu.icon} />
                <span style={spanStyle}>{menu.name}</span>
              </Link>
            </Menu.Item>
          );
        }
      } else {
        return null;
      }
    });
    return menuDom;
  }

  render = () => {
    const { current, collapsed, menuTheme } = this.props;
    const menuListJson = sessionStorage.getItem('loginMenu');
    const menuList = JSON.parse(menuListJson);
    const menu = this.createMenuItem(menuList, true);
    const openKeys = getOpenKeysByMenuKey(current, menuList);
    return (
      <Menu theme={menuTheme} defaultSelectedKeys={[current]} defaultOpenKeys={openKeys} mode={collapsed ? 'vertical' : 'inline'}>
        {menu}
      </Menu>
    );
  }
}
